# coding: utf-8

import json
from io import BytesIO
import time
import datetime
from timeit import timeit

import qrcode
from dateutil.relativedelta import relativedelta
from flask import request, make_response, Response
from fraMail.framail import FraMail
from flask import send_file, request
import QRcodeOper
from fralog.FraLog import getFileLog
from exceptions.fra_exception import FraException
# from fralog.kafka_logger import KafkaLogger
from settings import *
from dbproxy.dbproxy import *
from PIL import Image
# from flask import Flask, request, jsonify
import flask_excel as excel
from globalsettings import CUR_MODE
from sms.sms import FRA_SMS, customer_combine, INSURE_TIMES_LIMIT, create_4numrandom_pwd, create_new_insure_user

if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *
log = getFileLog()
LOG = log


class HRGeturlcollection(object):
    """
    hr客户信息页操作封装
    """
    table_name = 't_user'

    def __init__(self):
        super(HRGeturlcollection, self).__init__()
        self.db_proxy = DBProxy(db=mongo)

    def get_surveys_url(self, user_id):
        """
        根据user_id查询第一个问卷信息
        :param pagesize
        :param page
        :return:
        """
        log.debug('查询')
        log.debug('查询报告模板内容')
        user_item = self.db_proxy.query_one(table='t_user_product',
                                            query={'user_id': user_id, 'product_id': 'hr'})  # 获取公司名称或公司guid
        if user_item['count'] > 0:
            temp_company_id = user_item['data'][0]['company_id']
            LOG.debug('temp_company_id: %s' % temp_company_id)
            company_item = self.db_proxy.query_one(table='company_collection', query={'company_name': temp_company_id})
            if company_item.get('count') > 0:
                company_id = company_item['data'][0]['guid']
            else:
                company_id = temp_company_id
            LOG.debug('company_id = %s' % company_id)
            companyname_item = self.db_proxy.query_one(table='company_collection', query={'guid': company_id})
            print(companyname_item)
            if companyname_item.get('count') is None or companyname_item.get('count') == 0:
                return deepcopy(g_ret)
            company_name = companyname_item['data'][0]['company_name']
            ret1 = self.db_proxy.page_query(table='surveys_collection', query={'company_id': company_id},
                                            sort=[('create_time', pymongo.DESCENDING)])
            if ret1.get('count') <= 0:
                LOG.debug('公司id查询问卷失败,使用公司名称查询 company_name company_id = %s %s' % company_name, company_id)
                ret1 = self.db_proxy.page_query(table='surveys_collection', query={'company_id': company_name},
                                                sort=[('create_time', pymongo.DESCENDING)])
            ret1_count = 0
            datalist = []
            for item in ret1['data']:
                code = item['code']
                log.info(code)
                tempret = self.db_proxy.query_one(table='t_user_limit', query={'code': code})
                if tempret.get('count') > 0:
                    item['cur_times'] = tempret['data'][0].get('cur_times')
                    item['max_limit'] = tempret['data'][0].get('max_limit')
                else:
                    item['cur_times'] = 0
                    item['max_limit'] = 100000
                log.debug('查询成功返回')
                if 'job_cname' not in item.keys():
                    item['job_name'] = 'default'
                    item['job_cname'] = '默认'
                else:
                    datalist.append(item)
                    ret1_count = ret1_count + 1
            ret1['data'] = datalist
            ret1['count'] = ret1_count
            ret1['total_count'] = ret1_count
            return ret1
        return deepcopy(g_ret)

    def export_response_hr(self, code=None):
        '''
         根据岗位导出岗位下用户报告
         姓名，手机号码， 应聘岗位
        性别，年龄，毕业院校
        学历，专业
        特征1
        …
        特征10
        总分
        状态
        :param param:
        :return:
        '''
        ret = deepcopy(g_ret)
        response_list = {}
        code_jobname = 'xxx岗位'
        datestr = time.strftime('%Y%m%d', time.localtime(time.time()))
        response_list = self.db_proxy.page_query(table='responses_collection', query={'code': code},
                                                 sort=[('response.start', pymongo.DESCENDING)],
                                                 page=1, pagesize=10000)
        export__list = {}
        # 姓名,手机号码,应聘岗位,性别,年龄,毕业院校,学历,专业,总评分,状态
        # 姓名 571
        # 年龄 572
        # 性别 814
        # 您应聘的岗位 576
        # 您的手机号 575
        # 毕业院校 1228
        # 学历/学位 1234
        # 所学专业 1229
        comon_list1 = ["测试完成时间", "姓名", "手机号码", "应聘岗位", "应聘岗位所在地", "性别", "年龄", "毕业院校", "学历", "专业"]
        comon_list_spec = []
        comon_list_spec_id = []
        comon_list2 = ["总评分", "状态"]
        job_list = self.db_proxy.page_query(table='t_company_job', query={'code': code}, page=1, pagesize=1)
        if job_list.get('count') > 0:
            code_jobname = job_list.get('data')[0].get('job_cname')
        if len(response_list.get('data')) == 0:
            client_result_list = [comon_list1]
            return excel.make_response_from_array(array=client_result_list, file_type="xls",
                                                  file_name=code_jobname + datestr)
        else:
            for f_item in response_list.get('data')[0].get('feature_report').get('result'):
                comon_list_spec.append(f_item.get('dim'))
                comon_list_spec_id.append(f_item.get('rule_id'))
            client_result_list = [comon_list1 + comon_list_spec + comon_list2]

            for row in response_list.get('data'):
                response_item = row.get('response')
                name = ''
                phone = ''
                job_name = ''
                job_add = ''
                sex = ''
                old = ''
                school = ''
                edu_level = ''
                edu_pro = ''
                total_score = ''
                hr_status = ''
                try:
                    hr_status = response_item.get('hr_status')
                    if str(hr_status) == '1':
                        hr_status = '入选'
                    elif str(hr_status) == '0':
                        hr_status = '淘汰'
                    else:
                        hr_status = '尚未标记'
                except Exception as e:
                    pass

                try:
                    end = response_item.get('end')
                    # timeArray = time.localtime(str(end))
                    # strTime = time.strftime("%Y-%m-%d %H:%M:%S", localTime)
                    timeStruct = time.strptime(end, "%Y%m%d%H%M%S")
                    end_date = time.strftime('%Y-%m-%d %H:%M:%S', timeStruct)

                except Exception as e:
                    pass
                try:
                    total_score = row.get('get_feature').get('total_score')
                except Exception as e:
                    pass
                # params = ['571', '575', '576', '1383']
                # for param in params:
                #     try:
                #         name = response_item.get(param).get('answer')
                #     except Exception as e:
                #         pass
                try:
                    name = response_item.get('571').get('answer')
                except Exception as e:
                    pass
                try:
                    phone = str(response_item.get('575').get('answer'))
                except Exception as e:
                    pass
                try:
                    job_name = response_item.get('576').get('answer')
                except Exception as e:
                    pass
                try:
                    job_add = ''
                    if response_item.get('1383') is not None:
                        job_add = response_item.get('1383').get('answer')

                    job_adds = ['A北京', 'B上海', 'C深圳', 'D杭州', 'E南京', 'F广州', 'G成都', 'H厦门', 'I重庆', 'J武汉', 'K青岛',
                                'L大连', 'M天津', 'N佛山', 'O长沙', 'P宁波', 'Q云浮', 'R福州', 'S西安', 'T香港', 'U其他', 'V济南', 'W东莞', 'X苏州', 'Y沈阳']
                    if job_add:
                        for de in job_adds:
                            if str(job_add) == de[0:1]:
                                job_add = de[1:]
                except Exception as e:
                    pass

                try:
                    sex = response_item.get('814').get('answer')
                    if sex == 'A':
                        sex = '男'
                    else:
                        sex = '女'
                except Exception as e:
                    pass
                try:
                    old = response_item.get('572').get('answer')
                except Exception as e:
                    pass
                try:
                    school = response_item.get('1228').get('answer')
                except Exception as e:
                    pass
                try:
                    edu_level = response_item.get('1234').get('answer')
                    edus = ['A专科', 'B本科', 'C硕士', 'D博士', 'E其他']
                    if edu_level:
                        for ed in edus:
                            if str(edu_level) == ed[0:1]:
                                edu_level = ed[1:]
                    # if str(edu_level) == 'A':
                    #     edu_level = '专科'
                    # elif str(edu_level) == 'B':
                    #     edu_level = '本科'
                    # elif str(edu_level) == 'C':
                    #     edu_level = '硕士'
                    # elif str(edu_level) == 'D':
                    #     edu_level = '博士'
                    # else:
                    #     edu_level = '其他'
                except Exception as e:
                    pass
                try:
                    edu_pro = response_item.get('1229').get('answer')
                except Exception as e:
                    pass
                excel_comon_list_spec = []
                t_into = False
                for item in comon_list_spec_id:
                    t_into = False
                    for f_item in row.get('get_feature').get('score_list'):
                        if f_item.get('rule_id') == item:
                            excel_comon_list_spec.append(f_item.get('score'))
                            t_into = True
                    if t_into is False:
                        excel_comon_list_spec.append('')
                excel_comon_list1 = [end_date, name, phone, job_name, job_add, sex, old, school, edu_level, edu_pro]
                excel_comon_list2 = [total_score, hr_status]
                client_result_list.append(
                    excel_comon_list1 + excel_comon_list_spec + excel_comon_list2
                )

            return excel.make_response_from_array(array=client_result_list, file_type="xls",
                                                  sheet_name='sheet1',
                                                  file_name=code_jobname + datestr)

    def get_response_hr(self, pagesize, page, param_dict, code=None):
        """
        根据code查询答题结果倒叙
        :param pagesize
        :param page
        :return:
        """
        log.debug('查询报告模板内容: Code: %s' % code)
        report_type = None
        selected_survey = db.surveys_collection.find_one({"code": code})

        name = param_dict.get('name')
        contact = param_dict.get('contact')
        try:
            report_type = selected_survey['report_type']
        except Exception as e:
            pass
        if report_type == 'student':
            ret = self.db_proxy.page_query(table='responses_collection', sort=[('response.start', pymongo.DESCENDING)],
                                           query={'code': code, 'response.spider_status': 1}, page=page,
                                           pagesize=pagesize)
        else:
            query = {'code': code, '$or': []}
            if name is not None and name is not '':
                query['$or'].append({'response.571.answer': name})
            if contact is not None and contact is not '':
                query['$or'].append({'response.575.answer': int(contact)})
            if (name is not None and name is not '') or (contact is not None and contact is not ''):
                ret = self.db_proxy.page_query(table='responses_collection',
                                               sort=[('response.start', pymongo.DESCENDING)], query=query,
                                               page=page,
                                               pagesize=pagesize)
            else:
                ret = self.db_proxy.page_query(table='responses_collection',
                                               sort=[('response.start', pymongo.DESCENDING)],
                                               query={'code': code}, page=page,
                                               pagesize=pagesize)
        # ems = {'norm', 'bigFive', 'df_ocean', 'feature_report', 'featurelist', 'get_score', 'level', 'ocean_report',
        #        'wx_ocean', 'zocean'}
        # for item in ret.get('data'):
        #     for em in ems:
        #         if em in item:
        #             del item[em]
        for item in ret.get('data'):
            if 'norm' in item:
                del item['norm']
            if 'bigFive' in item:
                del item['bigFive']
            if 'df_ocean' in item:
                del item['df_ocean']
            if 'feature_report' in item:
                del item['feature_report']
            if 'featurelist' in item:
                del item['featurelist']
            # if 'get_feature' in item:
            #     del item['get_feature']
            if 'get_score' in item:
                del item['get_score']
            if 'level' in item:
                del item['level']
            if 'ocean_report' in item:
                del item['ocean_report']
            if 'wx_ocean' in item:
                del item['wx_ocean']
            if 'zocean' in item:
                del item['zocean']

            if 'job_name' not in item:
                if param_dict is None or param_dict.get('job_cname') is None:
                    item['job_name'] = 'default'
                    item['job_cname'] = '默认'
                else:
                    item['job_name'] = param_dict.get('job_name')
                    item['job_cname'] = param_dict.get('job_cname')
            qids = [571, 576, 1383, 814, 575, 572, 1228, 1234, 1229]
            delqids = []
            for k, v in item['response'].items():
                try:
                    qid = int(k)
                    if qid not in qids:
                        delqids.append(k)
                except Exception as e:
                    pass
            for id in delqids:
                del item['response'][id]
        print(ret)
        # if param_dict is None:
        #     ret = self.db_proxy.page_query(table='responses_collection', query={'code': code}, page=page, pagesize=pagesize,
        #                                    sort=[('response.start', pymongo.DESCENDING)])
        # else:
        #     list_query = []
        #     if param_dict.get('name') is not None:
        #         list_query.append({'response.571.answer': param_dict.get('name')})
        #     if param_dict.get('position') is not None:
        #         list_query.append({'response.576.answer': param_dict.get('position')})
        #     if param_dict.get('contact') is not None:
        #         list_query.append({'response.575.answer': param_dict.get('contact')})
        #     if param_dict.get('sex') is not None:
        #         list_query.append({'response.814.answer': param_dict.get('sex')})
        #     if param_dict.get('old') is not None:
        #         list_query.append({'response.572.answer': param_dict.get('old')})
        #     if param_dict.get('timeconsum1') is not None and param_dict.get('timeconsum2') is not None:
        #         gte_dict = {'$gte': int(param_dict.get('timeconsum1')), '$lte': int(param_dict.get('timeconsum2'))}
        #         list_query.append({'response.timeconsum': gte_dict})
        #     query_condition = {
        #                 'code': code, '$or':  list_query
        #             }
        #     ret = self.db_proxy.page_query(table='responses_collection', query=query_condition, page=page, pagesize=pagesize,
        #                                    sort=[('response.start', pymongo.DESCENDING)])
        log.debug('查询成功返回, 结果数: %s' % str(ret.get('count')))
        return ret

    def get_response_hrapi(self, pagesize, page, param_dict, start_day, end_day, code=None):
        """
        根据code查询答题结果倒叙
        :param pagesize
        :param page
        :return:
        """
        start_day = start_day + '000000'
        end_day = end_day + '240000'
        log.debug('查询报告模板内容: Code: %s' % code)
        report_type = None
        selected_survey = db.surveys_collection.find_one({"code": code})
        try:
            report_type = selected_survey['report_type']
        except Exception as e:
            pass
        if report_type == 'student':
            ret = self.db_proxy.page_query(table='responses_collection',
                                           sort=[('get_feature.total_score', pymongo.DESCENDING)],
                                           query={'code': code,
                                                  'response.spider_status': 1,
                                                  'response.end': {'$gt': start_day},
                                                  'response.end': {'$lt': end_day}
                                                  }, page=page, pagesize=pagesize)
        else:
            ret = self.db_proxy.page_query(table='responses_collection',
                                           sort=[('get_feature.total_score', pymongo.DESCENDING)],
                                           query={'code': code,
                                                  'response.end': {'$gt': start_day},
                                                  'response.end': {'$lt': end_day}
                                                  }, page=page, pagesize=pagesize)
            # ems = ['norm', 'bigFive', 'df_ocean', 'feature_report', 'featurelist', 'get_score', 'level', 'ocean_report',
            #        'wx_ocean', 'zocean']
            # for item in ret.get('data'):
            #     for em in ems:
            #         if em in item:
            #             del item[em]
            for item in ret.get('data'):

                if 'bigFive' in item:
                    del item['bigFive']
                if 'norm' in item:
                    del item['norm']
                if 'df_ocean' in item:
                    del item['df_ocean']
                if 'feature_report' in item:
                    del item['feature_report']
                if 'featurelist' in item:
                    del item['featurelist']
                    # if 'get_feature' in item:
                    #     del item['get_feature']
                if 'get_score' in item:
                    del item['get_score']
                if 'level' in item:
                    del item['level']
                if 'ocean_report' in item:
                    del item['ocean_report']
                if 'wx_ocean' in item:
                    del item['wx_ocean']
                if 'zocean' in item:
                    del item['zocean']
            if 'job_name' not in item:
                if param_dict is None or param_dict.get('job_cname') is None:
                    item['job_name'] = 'default'
                    item['job_cname'] = '默认'
                else:
                    item['job_name'] = param_dict.get('job_name')
                    item['job_cname'] = param_dict.get('job_cname')
            qids = [571, 576, 1383, 814, 575, 572, 1228, 1234, 1229]
            delqids = []
            for k, v in item['response'].items():
                try:
                    qid = int(k)
                    if qid not in qids:
                        delqids.append(k)
                except Exception as e:
                    pass
            for id in delqids:
                del item['response'][id]
        log.debug('查询成功返回, 结果数: %s' % str(ret.get('count')))
        return ret

    def get_response_insure(self, pagesize, page, userid, code=None):
        """
        保险接口：根据code查询答题结果倒叙
        :param pagesize
        :param page
        :return:
        """
        log.debug('获取顾客答卷列表: Code: %s' % code)
        item = db.t_user_limit.find_one({'user_id': userid, 'product_id': 'insure'}, sort=[('user_id', -1)])
        query = {'user_id': userid}
        if item is not None:
            code = item['code']
            query = {'user_id': userid, 'code': code}
        ret = self.db_proxy.page_query(table='responses_collection', sort=[('last_date', pymongo.DESCENDING)],
                                       query=query, page=page,
                                       pagesize=pagesize)

        for item in ret.get('data'):
            item_list = ['norm', 'bigFive', 'df_ocean', 'featurelist', 'get_feature', 'get_score', 'level',
                         'ocean_report', 'wx_ocean', 'zocean']
            for em in item_list:
                if em in item:
                    del item[em]
            # if 'norm' in item:
            #     del item['norm']
            # if 'bigFive' in item:
            #     del item['bigFive']
            # if 'df_ocean' in item:
            #     del item['df_ocean']
            # # if 'feature_report' in item:
            # #     del item['feature_report']
            # if 'featurelist' in item:
            #     del item['featurelist']
            # if 'get_feature' in item:
            #     del item['get_feature']
            # if 'get_score' in item:
            #     del item['get_score']
            # if 'level' in item:
            #     del item['level']
            # if 'ocean_report' in item:
            #     del item['ocean_report']
            # if 'wx_ocean' in item:
            #     del item['wx_ocean']
            # if 'zocean' in item:
            #     del item['zocean']

            qids = [571, 572, 814, 575]
            delqids = []
            for k, v in item['response'].items():
                try:
                    qid = int(k)
                    if qid not in qids:
                        delqids.append(k)
                except Exception as e:
                    pass
            for id in delqids:
                del item['response'][id]
        print(ret)
        log.debug('查询成功返回, 结果数: %s' % str(ret.get('count')))
        return ret

    def getqrcode_channel(self, path):
        qr = qrcode.QRCode(
            version=7,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4
        )
        qr.add_data(path)
        qr.make(fit=True)
        img = qr.make_image()
        img.save("channel_001.png")
        return img

    def getqrcode_channel_img(self, channel_no):
        qr = qrcode.QRCode(
            version=2,
            error_correction=qrcode.constants.ERROR_CORRECT_H,
            box_size=10,
            border=4
        )
        # "http://sales.fraplus.cn/#/login"
        #  https://itunes.apple.com/cn/app/sader/id1448225418
        # path = "http://fra.fraplus.cn/login/wxLogin?channel=" + str(
        #    channel_no) + "&stat=sales*v2&openid=null&fromid=&code=null&title=null"
        path = "https://itunes.apple.com/cn/app/sader/id1448225418"
        # 社恐下载地址
        # path = "https://shekong-1255423687.file.myqcloud.com/sader_file/e9ac33ebaa6a472cb040ead2cc013c94.apk"
        qr.add_data(path)
        qr.make(fit=True)

        img = qr.make_image()
        img = img.convert("RGBA")

        # icon = Image.open("pic_channel.png")
        icon = Image.open("sader.png")
        img_w, img_h = img.size
        factor = 4
        size_w = int(img_w / factor)
        size_h = int(img_h / factor)

        icon_w, icon_h = icon.size
        if icon_w > size_w:
            icon_w = size_w
        if icon_h > size_h:
            icon_h = size_h
        icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)

        w = int((img_w - icon_w) / 2)
        h = int((img_h - icon_h) / 2)
        icon = icon.convert("RGBA")
        img.paste(icon, (w, h), icon)
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        st = channel_no + '.png'
        img.save(st)
        # img.show()
        return str(st)

    def get_channel_no(self, channel_no):
        channel_info = db.t_channel_info.find_one({'channel_no': channel_no})
        if channel_info is not None:
            channel_no = create_4numrandom_pwd()
            self.get_channel_no(channel_no)
        else:
            return channel_no
        return 0


hrGeturlcollection = HRGeturlcollection()


@app.route('/hr/get_surveys_url', methods=['GET', 'POST'])
@verify_token
def hr_get_surveys_url():
    '''
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    g_user_id, ret = check_token(param.get('token'))
    # if param.get('token') == 'jim':
    #     g_user_id = 'test01'
    if g_user_id is None:
        return ret
    return jsonify(hrGeturlcollection.get_surveys_url(user_id=g_user_id))


@app.route('/hr/get_surveys_urlapi', methods=['GET', 'POST'])
def hr_get_surveys_urlapi():
    '''
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    appkey = str(param.get('appkey'))
    user_id = param.get('user_id')
    error_ret = deepcopy(g_ret)
    if appkey in APP_KEY_LIST:
        return jsonify(hrGeturlcollection.get_surveys_url(user_id=user_id))
    else:
        error_ret['msg'] = 'appkey fail'
        error_ret['code'] = 401
        return jsonify(error_ret)


@app.route('/hr/get_response_hr', methods=['GET', 'POST'])
@verify_token
def get_response_hr_list():
    '''
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug('查询问卷报告列表 ')

    param = get_param(request)
    code = param.get('code')
    # KafkaLogger().log_event(event='b_api', app='p_bole', user=code, level='info', msg=str(code) + '问卷响应列表查询',
    #                         status='200')
    job_cname = param.get('job_cname')
    job_name = param.get('job_name')
    page = int(param.get('page'))
    pagesize = int(param.get('pagesize'))
    name = param.get('name')  # 571 姓名
    position = param.get('position')  # 576  应聘岗位
    contact = param.get('contact')  # 575  手机号
    sex = param.get('sex')  # 814 性别
    old = param.get('old')  # 572  年龄
    school = param.get('school')  # 1228  学校
    major = param.get('major')  # 1229 专业
    education = param.get('education')  # 1234  学历/学位

    timeconsum1 = param.get('timeconsum1')
    timeconsum2 = param.get('timeconsum2')
    param_dict = None
    if name is None and position is None and contact is None and sex is None and old is None:
        pass
    else:
        param_dict = {'name': name, 'position': position, 'contact': contact, 'sex': sex, 'old': old,
                      'timeconsum1': timeconsum1, 'timeconsum2': timeconsum2, 'job_cname': job_cname,
                      'job_name': job_name, 'school': school, 'major': major, 'education': education}

    return json.dumps(hrGeturlcollection.get_response_hr(pagesize=pagesize,
                                                         page=page, code=code, param_dict=param_dict))


@app.route('/hr/hr_update_status', methods=['GET', 'POST'])
@verify_token
def hr_update_status():
    '''
    更新状态  -1：初始化（未选择），0：淘汰， 1：入选 ，
    :return:
    '''
    log.debug('更新入选状态')
    param = get_param(request)
    code = param.get("code")
    guid = param.get("guid")
    hr_status = param.get("hr_status")
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=guid, level='info', msg=str(code) + '更新入选状态',
    #                         status='200')
    ret = {}
    if code is None or code == '':
        ret['code'] = 500
        ret['msg'] = '参数不正确，code不可为空！'
        return json.dumps(ret)
    if guid is None or guid == '':
        ret['code'] = 500
        ret['msg'] = '参数不正确，guid不可为空！'
        return json.dumps(ret)
    if hr_status is not None:
        # info = db.responses_collection.update(
        #     {'code': code, 'guid': guid}, {'$set': {'response.hr_status': int(hr_status)}}, upsert=False)
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        ret = MongoOper.update(Wrapmongo(db=db), 'responses_collection', {'code': code, 'guid': guid},
                               {'$set': {'response.hr_status': int(hr_status), 'last_date': timestr}}, upsert=True)
    return json.dumps(ret)


@app.route('/hr/hr_update_score', methods=['GET', 'POST'])
@verify_token
def hr_update_score():
    '''
    更新评分结果
    feature_report.result.rule_id
    code
    guid
    :return:
    '''
    log.debug('更新入选状态')
    param = get_param(request)
    code = param.get("code")
    guid = param.get("guid")
    scores = param.get("scores")

    ret = {}
    if code is None or code == '':
        ret['code'] = 500
        ret['msg'] = '参数不正确，code不可为空！'
        return json.dumps(ret)
    if guid is None or guid == '':
        ret['code'] = 500
        ret['msg'] = '参数不正确，guid不可为空！'
        return json.dumps(ret)
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=guid, level='info',
    #                         msg=str(code) + '更新评分结果',
    #                         status='200')
    res = None
    if code is not None and guid is not None:
        response_list = MongoOper.find_one(Wrapmongo(db=db), 'responses_collection', {'code': code, 'guid': guid})
        result = response_list.get('data')[0].get('feature_report').get('result')
        if result is not None:
            for score in scores:
                if score['rule_id'] is not None and score['score'] is not None:
                    for res in result:
                        if res.get('rule_id') == score.get('rule_id'):
                            res['score'] = score['score']
            timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            ret = MongoOper.update(Wrapmongo(db=db), 'responses_collection',
                                   {'code': code, 'guid': guid},
                                   {'$set': {'feature_report.result': result, 'last_date': timestr}}, upsert=False)

        ret['code'] = 200
        ret['msg'] = '保存成功！'

    return json.dumps(ret)


@app.route('/hr/hr_update_note', methods=['GET', 'POST'])
@verify_token
def hr_update_note():
    '''
    更新自定义标签
    :return:
    '''
    log.debug('更新报告自定义标签')
    param = get_param(request)
    code = param.get("code")
    guid = param.get("guid")
    note = param.get("note")
    ret = {}
    if code is None or code == '':
        ret['code'] = 500
        ret['msg'] = '参数不正确，code不可为空！'
        return json.dumps(ret)
    if guid is None or guid == '':
        ret['code'] = 500
        ret['msg'] = '参数不正确，guid不可为空！'
        return json.dumps(ret)
    if note is not None:
        # ret = db.responses_collection.update(
        #     {'code': code, 'guid': guid}, {'$set': {'response.note': note}}, upsert=False)
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        ret = MongoOper.update(Wrapmongo(db=db), 'responses_collection', {'code': code, 'guid': guid},
                               {'$set': {'response.note': note, 'last_date': timestr}}, upsert=True)

    return json.dumps(ret)


@app.route('/hr/export_response_hr', methods=['GET', 'POST'])
@verify_token
def export_response_hr_bycode():
    '''
     报告列表下载
    :return:
    '''
    log.debug('导出岗位下报告列表')
    param = get_param(request)
    code = param.get('code')
    return hrGeturlcollection.export_response_hr(code=code)


@app.route('/insure/export_wxin_insure', methods=['GET', 'POST'])
def exel_wxin_insure():
    '''
     微信信息下载
       这里下载微信信息需要切换数据库 --下载微信头像，昵称项目
    :return:
    '''
    log.debug('导出岗位下报告列表')
    param = get_param(request)
    openids = param.get('openids')
    return hrGeturlcollection.export_wxin_insure(openids=openids)


@app.route('/insure/get_channel_primg', methods=['GET', 'POST'])
# @verify_token
def get_prCode():
    '''
    根据渠道商编号生成渠道二维码
    '''
    param = get_param(request)
    ret = deepcopy(g_ret)
    channel_no = param.get('channel_no')
    LOG.debug('获取渠道注册二维码！')
    # img = hrGeturlcollection.getqrcode_channel(path)
    if channel_no is None:
        ret['code'] = 400
        ret['msg'] = '参数错误，生成失败！'
        return ret
    img = hrGeturlcollection.getqrcode_channel_img(channel_no)
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=channel_no, level='info',
    #                         msg=str(channel_no) + '根据渠道商编号生成渠道二维码',
    #                         status='200')
    msstream = BytesIO()
    # RGBA  JPEG
    # img.save(msstream, "jpeg")
    # img.close()
    # resp = Response(msstream.getvalue(), mimetype="image/jpeg")
    # img.show()
    ret['code'] = 200
    ret['data'] = 'http://fra.fraplus.cn/login/wxLogin?channel=' + str(
        channel_no) + '&stat=sales*v2&openid=null&fromid=&code=null&title=null'
    ret['msg'] = '生成成功！'
    return send_file(img, mimetype='image/png', cache_timeout=0)


# return jsonify(ret)


@app.route('/insure/addChannel', methods=['GET', 'POST'])
# @verify_token
def set_channel():
    '''
     新增渠道信息 addChannel
    :return:
    '''
    ret = deepcopy(g_ret)
    log.debug('新增渠道信息')
    param = get_param(request)
    tel = param.get('tel')
    channel_name = param.get('channel_name')
    email = param.get('email')
    nickname = param.get('nickname')
    no = create_4numrandom_pwd()
    channel_no = hrGeturlcollection.get_channel_no(no)
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=tel, level='info', msg=str(channel_name) + '渠道商注册接口',
    #                         status='200')
    db.t_channel_info.update(
        {'channel_no': channel_no}, {'$set': {'channel_no': channel_no,
                                              'channel_name': channel_name,
                                              'tel': int(tel),
                                              'status': 0,  # 0试用 1 正式，2禁用
                                              'email': email,
                                              'create_date': time.strftime('%Y-%m-%d %H:%M:%S',
                                                                           time.localtime(time.time())),
                                              'nickname': nickname
                                              }},
        upsert=True
    )
    ret['code'] = 200
    ret['data'] = channel_no
    ret['msg'] = '新增成功！'
    return jsonify(ret)


@app.route('/insure/addCache', methods=['GET', 'POST'])
def set_cache():
    '''
     获取全部用户存入缓存
	 TODO 测试用户缓存接口
    :return:
    '''
    import diskcache as dc
    ret = deepcopy(g_ret)
    log.debug('增加缓存')
    user_lists = db.t_user.find()
    cache = dc.Cache('user_cache')
    list = []
    for row in user_lists:
        if '_id' in row:
            del row['_id']
        list.append(row)
    cache['user'] = list
    ret['code'] = 200
    ret['data'] = cache['user']
    ret['msg'] = '缓存添加成功！'
    return jsonify(ret)


@app.route('/insure/matchUser', methods=['GET', 'POST'])
def match_cache():
    '''
     用户缓存匹配
	 TODO 缓存匹配测试
    :return:
    '''
    import diskcache as dc
    ret = deepcopy(g_ret)
    log.debug('增加缓存')
    param = get_param(request)
    user = param.get('user')
    pwd = param.get('pwd')
    cache = dc.Cache('user_cache')
    items = cache['user']
    for item in items:
        if user == item['user_id']:
            if pwd == item['pwd']:
                del item['pwd']
                ret['code'] = 200
                ret['data'] = item
                ret['msg'] = '登录成功'
                return jsonify(ret)
            else:
                ret['code'] = 400
                ret['data'] = 0
                ret['msg'] = '密码不匹配！'
                return jsonify(ret)
    ret['code'] = 400
    ret['data'] = 0
    ret['msg'] = '用户不存在！'
    return jsonify(ret)


@app.route('/insure/getChannelUsers', methods=['GET', 'POST'])
@verify_token
def get_channeluser():
    '''
     根据渠道编号，获取用户列表
    :return:
    '''
    ret = deepcopy(g_ret)
    log.debug('获取渠道')
    param = get_param(request)
    user = param.get('user')
    channel_no = param.get('channel_no')
    start_date = param.get('start_date')
    end_date = param.get('end_date')
    now_time = datetime.datetime.now()
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=user, level='info',
    #                         msg=str(channel_no) + '根据渠道编号获取用户列表',
    #                         status='200')
    if channel_no is None:
        chananel = db.t_user_limit.find_one({'code': code, 'user': user})
        if chananel is not None:
            channel_no = chananel.get('channel_no')
    if channel_no is None or channel_no == '':
        ret['code'] = 400
        ret['msg'] = '渠道为空，查询失败！'
        return jsonify(ret)
    # 查询所有用户
    if start_date is not None and start_date is not '':
        start_date = time.strptime(str(start_date), "%Y-%m-%d")
        start_str = time.strftime("%Y-%m-%d %H:%M:%S", start_date)
    else:
        start_str = datetime.datetime(now_time.year, now_time.month, 1)
        # start_date = (date.today() + timedelta(days=-1)).strftime("%Y-%m-%d")
    if end_date is not None and end_date is not '':
        end_date = time.strptime(str(end_date), '%Y-%m-%d')
        end_str = time.strftime("%Y-%m-%d %H:%M:%S", end_date)
    else:
        month = now_time.month
        if month == 12:
            month = 0
        end_str = datetime.datetime(now_time.year, month + 1, 1)
        # end_date = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")
    total_aumonts = 0.0
    res_users = []
    try:
        user_list = db.t_user.find({'channel_no': channel_no, "create_date": {"$gt": start_str, "$lt": end_str}})
        if user_list is not None:
            for item in user_list:
                user_info = {}
                if '_id' in item:
                    del item['_id']
                user_info['user_id'] = item['user_id']
                user_info['acount_type'] = item['acount_type']
                user_info['channel_no'] = item['channel_no']
                user_info['status_desc'] = '注册试用'
                user_info['total_amount'] = 0
                user_info['order_no'] = ''
                create_date = item['create_date']
                if create_date:
                    date = datetime.datetime.strptime(create_date, '%Y-%m-%d %H:%M:%S')
                    date_d = date + relativedelta(months=+1)
                    detester = date_d.strftime('%Y-%m-%d')
                user_info['deadline'] = detester
                user_info['create_date'] = item['create_date']
                res_users.append(user_info)
        order_list = db.t_pay_order.find(
            {'channel_no': channel_no, 'status': 1, "start_time": {"$gt": start_str, "$lt": end_str}})
        if order_list is not None:
            for item in order_list:
                order_info = {}
                if '_id' in item:
                    del item['_id']
                    order_info['user_id'] = item.get('user_id')
                    order_info['acount_type'] = '2'
                    order_info['channel_no'] = item.get('channel_no')
                    order_info['status_desc'] = '付费会员'
                    order_info['order_no'] = item.get('order_no')
                    order_info['total_amount'] = item.get('total_amount')
                    total_amount = item.get('total_amount')
                    order_info['deadline'] = item.get('dead_line')
                    order_info['create_date'] = item.get('start_time')
                    if total_amount is not None:
                        total_aumonts = float(total_aumonts) + float(total_amount)
                    res_users.append(order_info)
    except Exception as e:
        ret['code'] = 500
        ret['msg'] = '系统异常！: %s' % e
        return jsonify(ret)

    ret['code'] = 200
    ret['total_aumonts'] = total_aumonts
    ret['data'] = res_users
    ret['msg'] = '查询成功！'
    return jsonify(ret)


@app.route('/user/channel_register', methods=['GET', 'POST'])
def channel_register():
    # 渠道注册，提交注册

    param = get_param(request)
    channel_no = param.get("channel_no")
    pwd = param.get("pwd")
    user = param.get("user")
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=user, level='info', msg=str(code) + '渠道注册接口',
    #                         status='200')
    company_id = user
    ret = deepcopy(g_ret)
    chananel = db.t_user_limit.find_one({'channel_no': channel_no, 'code': code, 'user': user})
    if chananel is not None:
        ret['code'] = 401
        ret['msg'] = '用户已存在！'
    else:
        value = {'user': user, 'product_id': 'insure'}
        ret = customer_combine.insert4BXJJR(value=value)
        if ret['code'] == 200:
            survey_code = ret['survey_code']
            limit_times = INSURE_TIMES_LIMIT
            LOG.write_log('send try account', event='try', code=survey_code, product_id='insure', user=user)
            flag = create_new_insure_user(user=user, pwd=pwd, code=survey_code, product_id='insure', acount_type=1,
                                          company_id=company_id)
            if flag:
                ret['code'] = 200
                ret['msg'] = '创建成功！'
                ret['msg_flag'] = 'success'
                return json.dumps(ret)
            else:
                ret['code'] = 404
                ret['msg'] = '用户名重复！'
                ret['msg_flag'] = 'userid is duplication'
    return jsonify(ret)


@app.route('/hr/test_dead_line', methods=['GET', 'POST'])
def date_line():
    param = get_param(request)
    code = param.get("code")
    user = param.get("user")
    ret = deepcopy(g_ret)

    user_limit = db.t_user_limit.find_one({'user_id': user, 'code': code})
    now_date = datetime.date.today()
    print(int(time.time()))
    # datetime.date.today() + relativedelta(months=+1)
    times = datetime.date.today() + relativedelta(months=+1)
    # print(time.localtime(times))
    timeStamp = 1381419600
    dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
    threeDayAgo = dateArray + datetime.timedelta(days=30)
    print(threeDayAgo)
    db.t_user_limit.update({'code': code, 'user_id': user}, {'$set': {'dead_line': int(time.time())}})
    dead_line = None
    date_str = None
    ret['code'] = 200
    ret['msg'] = '查询成功！'
    if user_limit is not None:
        dead_line = user_limit.get('dead_line')
        if dead_line is not None:
            if now_date > date_str:
                ret['code'] = 400
                ret['msg'] = '用户已过期！'

    return jsonify(ret)


@app.route('/hr/get_response_hr_excel_api', methods=['GET', 'POST'])
@verify_token
def hr_get_response_hrapi():
    '''
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    appkey = str(param.get('appkey'))
    outtype = param.get('outtype')
    error_ret = deepcopy(g_ret)
    f_company_id = None
    if appkey in APP_KEY_LIST:
        f_company_id = appkey.split('_')[0]
    else:
        error_ret['msg'] = 'appkey fail'
        error_ret['code'] = 401
        return json.dumps(error_ret)
    del param['appkey']
    code = param.get('code')
    start_day = param.get('start_day')
    end_day = param.get('end_day')
    job_cname = param.get('job_cname')
    job_name = param.get('job_name')
    page = int(param.get('page'))
    pagesize = int(param.get('pagesize'))
    name = param.get('name')  # 571
    position = param.get('position')  # 576
    contact = param.get('contact')  # 575
    sex = param.get('sex')  # 814
    old = param.get('old')  # 527
    timeconsum1 = param.get('timeconsum1')
    timeconsum2 = param.get('timeconsum2')
    param_dict = None
    if name is None and position is None and contact is None and sex is None and old is None:
        pass
    else:
        param_dict = {'name': name, 'position': position, 'contact': contact, 'sex': sex, 'old': old,
                      'timeconsum1': timeconsum1, 'timeconsum2': timeconsum2, 'job_cname': job_cname,
                      'job_name': job_name}
    ret = hrGeturlcollection.get_response_hrapi(start_day=start_day, end_day=end_day, pagesize=pagesize, page=page,
                                                code=code,
                                                param_dict=param_dict)
    if outtype is None or outtype == 'json':
        return jsonify(ret)
    else:
        client_result_list = []
        client_result_list = [["总数", "总页数", "页", "每页大小", "部分信息", "得分记录"]]
        for row in ret.get('data'):
            client_result_list.append([
                ret.get('total_count'), ret.get('total_page'), ret.get('page'), ret.get('pagesize'),
                json.dumps(row.get('response'), ensure_ascii=False),
                json.dumps(row.get('get_feature'), ensure_ascii=False)
            ])
        return excel.make_response_from_array(client_result_list, "xls",
                                              file_name="response_data_" + create_4random_pwd())


@app.route('/hr/get_response_insure', methods=['GET', 'POST'])
@verify_token
def get_response_insure_list():
    '''
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug('查询问卷报告列表 ')
    param = get_param(request)
    code = param.get('code')
    userid = param.get('userid')
    page = int(param.get('page'))
    pagesize = int(param.get('pagesize'))
    # KafkaLogger().log_event(event='b_api', app='p_aggent', user=userid, level='info', msg=str(code) + '查询问卷报告列表',
    #                         status='200')
    return json.dumps(hrGeturlcollection.get_response_insure(pagesize=pagesize,
                                                             page=page, code=code, userid=userid))
